package id.co.gomobile.assessment

class RegistrationController {
	
	static allowedMethods = [submit: "POST"]
	
	def authenticateService
	def registrationService
	
    def index = {
    	redirect(action: "signup")
    }
	
	def signup = {
		def userInstance = new User()
		userInstance.properties = params
		return [userInstance: userInstance]
	}

	def submit = {
		def userInstance = new User(params)
		def password = registrationService.createRandomPassword()
		userInstance.password = authenticateService.encodePassword(password)
		if (!userInstance.hasErrors() && userInstance.save(flush: true)) {
			Role.findByName("ROLE_USER").addToUsers(userInstance)
			
			_sendRegistrationEmail(userInstance, password)
			
			flash.message = "${message(code: 'default.signup.message')}"
			redirect(uri: "/")
		}
		else {
			render(view: "signup", model: [userInstance: userInstance])
		}
	}

	/**
	 * Activation email after registration
	 * 
	 * TODO: load template from email
	 */
	def _sendRegistrationEmail = { userInstance, password ->
		sendMail {
		 	to userInstance.email
		 	subject "${message(code: 'email.registration.subject')}"
		 	body (view: "/shared/emails/registration", model: [userInstance: userInstance, password: password])
		}
	}

}
